//xml -> json
import xml2json from 'xml2js';
const xmlParserToJson = new xml2json.Parser();
import superagent from 'superagent';

const getAccessToken = (code, appid, appkey, redirect_uri) => {
    return new Promise((yes, no) => {
        let Authorization = new Buffer(`${appid}:${appkey}`).toString('base64');
        superagent.post('https://ose.caiyun.feixin.10086.cn/oauthApp/OAuth2/getToken').set({
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': `Basic ${Authorization}`
        }).timeout(1000 * 10).send({
            grant_type: 'authorization_code',
            code: code,
            redirect_uri: redirect_uri
        }).end((err, res) => {
            if (err) return no(err);
            yes(res.body);
        });
    });
};

const refreshToken = (appid, appkey, refresh_token) => {
    return new Promise((yes, no) => {
        let Authorization = new Buffer(`${appid}:${appkey}`).toString('base64');
        superagent.post('https://ose.caiyun.feixin.10086.cn/oauthApp/OAuth2/refreshToken').set({
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': `Basic ${Authorization}`
        }).timeout(1000 * 10).send({
            grant_type: 'refresh_token',
            refresh_token: refresh_token
        }).end((err, res) => {
            if (err) return no(err);
            yes(res.body);
        });
    });
};

const getFileList = (AccessToken, folderid = 'root', startNumber = 1, endNumber = 50) => {
    return new Promise((yes, no) => {
        superagent.post('http://ose.caiyun.feixin.10086.cn/richlifeApp/devapp/ICatalog').set({
            'Content-Type': 'text/xml;UTF-8',
            'Authorization': `Bearer ${AccessToken.toString('base64')}`,
        }).send(`<?xml version="1.0" encoding="utf-8"?>
        <getDisk>
            <MSISDN>thirdparty_anonymous_account</MSISDN>
            <catalogID>${folderid}</catalogID>
            <entryShareCatalogID></entryShareCatalogID>
            <filterType>0</filterType>
            <catalogSortType>1</catalogSortType>
            <contentType>0</contentType>
            <contentSortType>1</contentSortType>
            <sortDirection>0</sortDirection>
            <startNumber>${startNumber}</startNumber>
            <endNumber>${endNumber}</endNumber>
            <channelList></channelList>
            <catalogType>-1</catalogType>
        </getDisk>`).timeout(1000 * 10).buffer(true).end((err, res) => {
                if (err) return no(err);
                xmlParserToJson.parseString(res.text, (error, result) => {
                    if (error) return no(error);
                    yes(result);
                });
            });
    });
};

const getDownload = (AccessToken, fileid, phone) => {
    return new Promise((yes, no) => {
        superagent.post('https://ose.caiyun.feixin.10086.cn/richlifeApp/devapp/IUploadAndDownload').set({
            'Content-Type': 'text/xml;UTF-8',
            'Authorization': `Bearer ${AccessToken.toString('base64')}`,
        }).send(`<?xml version="1.0" encoding="utf-8"?>
        <downloadRequest>
            <appName>gakkicloud</appName>
            <MSISDN>thirdparty_anonymous_account</MSISDN>
            <contentID>${fileid}</contentID>
            <OwnerMSISDN>${phone}</OwnerMSISDN>
            <entryShareCatalogID></entryShareCatalogID>
        </downloadRequest>`).timeout(1000 * 10).buffer(true).end((err, res) => {
                if (err) return no(err);
                xmlParserToJson.parseString(res.text, (error, result) => {
                    if (error) return no(error);
                    yes(result);
                });
            });
    });
};

const deleteFile = (AccessToken = '', filelist = [], forlderlist = []) => {
    let parse = eval(compile(`<?xml version="1.0" encoding="utf-8"?>
    <delCatalogContent>
    <ownerMSISDN>thirdparty_anonymous_account</ownerMSISDN>
    <catalogIDs length="0">
    </catalogIDs>
    <contentIDs length="${filelist.length}">
    <% for (let i = 0; i < filelist.length; i++) { %>
        <ID><%= filelist[i] %></ID>
    <% } %>
    </contentIDs>
    <contentURLs length="${forlderlist.length}">
    <% for (let i = 0; i < forlderlist.length; i++) { %>
        <ID><%= forlderlist[i] %></ID>
    <% } %>
    </contentURLs>
    <oprReason>0</oprReason>
    </delCatalogContent>`));
    return new Promise((yes, no) => {
        superagent.post('https://ose.caiyun.feixin.10086.cn/richlifeApp/devapp/IContent').set({
            'Content-Type': 'text/xml;UTF-8',
            'Authorization': `Bearer ${AccessToken.toString('base64')}`,
        }).send(parse({ filelist, forlderlist })).timeout(1000 * 10).buffer(true).end((err, res) => {
                if (err) return no(err);
                xmlParserToJson.parseString(res.text, (error, result) => {
                    if (error) return no(error);
                    yes(result);
                });
            });
    });
};

const deleteAllUpload = (AccessToken, uploadTaskID, fileName) => {
    return new Promise((yes, no) => {
        superagent.post('https://ose.caiyun.feixin.10086.cn/richlifeApp/devapp/IUploadAndDownload').set({
            'Content-Type': 'text/xml;UTF-8',
            'Authorization': `Bearer ${AccessToken.toString('base64')}`,
        }).send(`<?xml version="1.0" encoding="utf-8"?>
        <delUploadTask>
        <account>thirdparty_anonymous_account</account>
        <taskID>${uploadTaskID}</taskID>
        <fileName>${fileName}</fileName>
        </delUploadTask>`).timeout(1000 * 10).buffer(true).end((err, res) => {
                if (err) return no(err);
                xmlParserToJson.parseString(res.text, (error, result) => {
                    if (error) return no(error);
                    yes(result);
                });
            });
    })
};

const getUploadFileUrl = (AccessToken, { folderid, filename, filesize, file_md5 }) => {
    return new Promise((yes, no) => {
        superagent.post('https://ose.caiyun.feixin.10086.cn/richlifeApp/devapp/IUploadAndDownload').set({
            'Content-Type': 'text/xml;UTF-8',
            'Authorization': `Bearer ${AccessToken.toString('base64')}`,
        }).send(`<?xml version="1.0" encoding="utf-8"?>
        <pcUploadFileRequest>
            <ownerMSISDN>thirdparty_anonymous_account</ownerMSISDN>
            <fileCount>1</fileCount>
            <totalSize>${filesize}</totalSize>
            <uploadContentList length="1">
                <uploadContentInfo>
                    <contentName>${filename}</contentName>
                    <contentSize>${filesize}</contentSize>
                    <contentDesc></contentDesc>
                    <contentTAGList></contentTAGList>
                    <comlexFlag>0</comlexFlag>
                    <comlexCID>var_null</comlexCID>
                    <resCID length="0">
                    </resCID>
                    <digest>${file_md5}</digest>
                </uploadContentInfo>
            </uploadContentList>
            <newCatalogName></newCatalogName>
            <parentCatalogID>${folderid}</parentCatalogID></pcUploadFileRequest>`).timeout(1000 * 10).buffer(true).end((err, res) => {
                if (err) return no(err);
                xmlParserToJson.parseString(res.text, (error, result) => {
                    if (error) return no(error);
                    yes(result);
                });
            });
    })
};

/**
 * 字符串模板解析函数
 * 
 * @param {String} template 
 * @returns {String} script 需要eval解析
 */
function compile(template) {
    const evalExpr = /<%=(.+?)%>/g;
    const expr = /<%([\s\S]+?)%>/g;

    template = template
        .replace(evalExpr, '`); \n  echo( $1 ); \n  echo(`')
        .replace(expr, '`); \n $1 \n  echo(`');

    template = 'echo(`' + template + '`);';

    let script =
`(function parse(data){
    let output = "";
    function echo(html){
        output += html;
    }
    ${ template }
    return output;
})`;

    return script;
}

export default {
    getAccessToken,
    refreshToken,
    getFileList,
    getDownload,
    deleteFile,
    deleteAllUpload,
    getUploadFileUrl
}